<?php

class Activity_Model_ObjectRef extends Euso_ObjectRef
{
	protected $_activityId = NULL;
	protected $_role = NULL;


    public function __construct($activityId = NULL, $role = NULL,
		$objClassIdName = NULL, $objId = NULL, $objIdName = NULL)
    {
		$this->_activityId = $activityId;
		$this->_role = $role;
		parent::__construct($objClassIdName, $objId, $objIdName);
    }


	public function setActivityId($activityId = NULL)
	{
		$this->_activityId = $activityId;
		return $this;
	}
	public function setRole($role = NULL)
	{
		$this->_role = $role;
		return $this;
	}

	public function getActivityId()
	{
		return $this->_activityId;
	}
	public function getRole()
	{
		return $this->_role;
	}


    public function __set($name, $value)
    {
        $method = 'set' . ucfirst($name);
        $this->$method($value);
    }
    public function __get($name)
    {
        $method = 'get' . ucfirst($name);
        return $this->$method();
    }



//	protected static $_instanceList = array();


	/**
	 * Queries for an instance. If the instance is not found, it will be loaded from the database.
	 */

	public static function getInstancesByActivityId($activityId = NULL)
	{
		if (intval($activityId) === 0) {
			return array();
		}


		$instances = array();


		$table = Activity_Model_DbTable_Object::getInstance();

		//TODO: filters
		$select = $table->select();
		$select
			->where('activity_id= ?', $activityId)
		;

		$dbResult = $table->fetchAll($select);

		//TODO: caching
		foreach ($dbResult as $dbRow) {
//			if (isset(self::$_instanceList[$dbRow->activity_id])) {
//				$instances[] = self::$_instanceList[$dbRow->activity_id];
//			} else {
				$inst = new Activity_Model_ObjectRef();
				$inst
					->setActivityId($dbRow->activity_id)
					->setRole($dbRow->role)
					->setObjectClassIdName($dbRow->object_class)
					->setObjectId($dbRow->object_id)
				;

//				self::$_instanceList[$dbRow->id] = $inst;
				$instances[] = $inst;
//			}
		}

		return $instances;
	}
	public static function getInstancesByObject($classIdName, $objectId)
	{
		if (empty($classIdName)) {
			return array();
		}
		if (intval($objectId) < 1) {
			return array();
		}


		$instances = array();


		$table = Activity_Model_DbTable_Object::getInstance();

		//TODO: filters
		$select = $table->select();
		$select
			->where('object_class= ?', $classIdName)
			->where('object_id= ?', $objectId)
		;

		$dbResult = $table->fetchAll($select);

		//TODO: caching
		foreach ($dbResult as $dbRow) {
//			if (isset(self::$_instanceList[$dbRow->activity_id])) {
//				$instances[] = self::$_instanceList[$dbRow->activity_id];
//			} else {
				$inst = new Activity_Model_ObjectRef();
				$inst
					->setActivityId($dbRow->activity_id)
					->setRole($dbRow->role)
					->setObjectClassIdName($dbRow->object_class)
					->setObjectId($dbRow->object_id)
				;

//				self::$_instanceList[$dbRow->id] = $inst;
				$instances[] = $inst;
//			}
		}

		return $instances;
	}
}
